<!-- 待办事项页面 -->
<script setup lang="ts">
import { ref, onMounted, useTemplateRef } from 'vue'
import Container from '@/components/Container/index.vue'
import { queryTodoList, addTodo, completeTodo } from '@/api/todo.ts'
import { ElMessage } from 'element-plus'
import { StorageEnum } from '@/common/enums'
import AddDialog from './components/AddDialog.vue'
import type { TodoVO } from '@/interface'
import type { CollapseModelValue } from 'element-plus'

defineOptions({
  name: 'Todo',
})

const loading = ref(false)

// 获取用户id
const userId = localStorage.getItem(StorageEnum.USER_ID)
const dataList = ref<TodoVO[]>([])
const getTodoList = async () => {
  // 获取用户ID
  if (!userId) return
  loading.value = true
  const result = await queryTodoList({ createdBy: Number(userId) })
  loading.value = false
  if (!Array.isArray(result)) return
  dataList.value = result
}
onMounted(getTodoList)

const activeNames = ref<number[]>([])
const handleChange = (val: CollapseModelValue) => {
  console.log(val)
}

const addRef = useTemplateRef<InstanceType<typeof AddDialog>>('addDialogRef')

const openAddDialog = () => {
  if (!addRef.value) return
  addRef.value.open()
}

const addTodoHandler = async (data: Omit<TodoVO, 'id' | 'isEnd'>) => {
  if (!userId) return
  loading.value = true
  await addTodo({ ...data, createdBy: Number(userId) })
  loading.value = false
  ElMessage.success('新增成功')
  await getTodoList()
}

// 完成待办
const toggleTodo = async (id: number) => {
  await completeTodo({ id })
  await getTodoList()
}
</script>

<template>
  <Container
    class="todo-manager"
    title="待办事项"
    search
    :columns="['add']"
    @on:add="openAddDialog"
    v-loading="loading"
  >
    <el-scrollbar>
      <el-collapse v-model="activeNames" @change="handleChange">
        <el-collapse-item
          v-for="item in dataList"
          :key="item.id"
          :name="item.id"
        >
          <template #title>
            <el-checkbox
              :checked="!!item.isEnd"
              :disabled="!!item.isEnd"
              @click.stop
              @change="toggleTodo(item.id)"
            />
            <div :class="{ completed: item.isEnd }" style="margin-left: 10px">
              {{ item.title }}
            </div>
          </template>
          <!-- <template #icon>
            <span>111</span>
          </template> -->
          <div>
            {{ item.description }}
          </div>
        </el-collapse-item>
      </el-collapse>
    </el-scrollbar>
  </Container>
  <AddDialog ref="addDialogRef" @on:submit="addTodoHandler" />
</template>

<style>
.todo-manager {
  .completed {
    text-decoration: line-through;
    color: #999;
  }
}
</style>
